package com.rapida.theme;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;

import com.rapida.framwork.RapidActivity;

import java.util.ArrayList;

public abstract class RapidThemeActivity extends Activity {
	private ThemeManager mThemeManager;
	private ThemeResources mThemeRes;
	private SharedPreferences mPreferences;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		mThemeRes = new ThemeResources(this);
		mThemeManager = ThemeManager.get(getBaseContext());
		mThemeManager.searchTheme();
		mPreferences = getSharedPreferences("ThemePlugin", Context.MODE_PRIVATE);
		super.onCreate(savedInstanceState);
		applyTheme(getThemePackageName());
	}

	protected abstract void OnThemeChanged(String newThemePackageName);

	public String getThemePackageName() {
		return mPreferences.getString("themePackageName", getPackageName());
	}

	public ArrayList<ThemeInfo> getThemes() {
		return mThemeManager.getThemes();
	}

	public ThemeResources getThemeResources() {
		return mThemeRes;
	}

	private boolean setThemeContext(String newThemePackageName) {
		if (newThemePackageName == null) {
			return false;
		}
		try {
			Context themeContext = createPackageContext(newThemePackageName, CONTEXT_IGNORE_SECURITY);
			mThemeRes.setThemeContext(themeContext);
		} catch (NameNotFoundException e) {
			return false;
		}
		return true;
	}

	public void applyTheme(String newThemePackageName) {
		if (setThemeContext(newThemePackageName)) {
			savePerference(newThemePackageName);
			OnThemeChanged(newThemePackageName);
		}
	}

	public void applyTheme(ThemeInfo theme) {
		if (theme != null) {
			applyTheme(theme.packageName);
		}
	}

	private void savePerference(String newThemePackageName) {
		Editor edit = mPreferences.edit();
		edit.putString("themePackageName", newThemePackageName);
		edit.commit();
	}

}
